<template>
  <div class="dc-container">
    <!-- 根据业务字段多少，决定弹窗合理宽度 -->
    <!-- ❌ 不要使用v-model:visible -->
    <el-dialog v-model="visible" width="50%"
      :fullscreen="false" :title="title" :close-on-click-modal="false"
      @open="onDialogOpen" @close="onDialogClose">
      <el-form ref="editForm" :model="form" :rules="rules" label-width="100px" :disabled="mode == 'view'">
        <!-- 根据数据库字段生成表单项, 根据业务合理布局 -->
        <el-form-item prop="parent.id" label="父级" class="dc-el-form-item_CascaderInput">
          <el-cascader ref="parentCascader" :options="parentOptions" v-model="form.parent.id" :style="{ width: '100%' }" placeholder="请选择父级" separator="/"
            :props="{ label: 'name', value: 'id', children: 'children', checkStrictly: true, emitPath: false }"
            filterable clearable></el-cascader>
        </el-form-item>

        <el-form-item prop="code" label="编号">
          <el-input v-model="form.code" :maxLength="64" placeholder="请输入编号" clearable></el-input>
        </el-form-item>

        <el-form-item prop="name" label="名称">
          <el-input v-model="form.name" :maxLength="128" placeholder="请输入名称" clearable></el-input>
        </el-form-item>

        <el-form-item prop="full_name" label="全称">
          <el-input v-model="form.fullName" :maxLength="512" placeholder="请输入全称" clearable></el-input>
        </el-form-item>

        <el-form-item prop="sort" label="排序">
          <el-input-number v-model="form.sort" :min="0" placeholder="请输入排序"></el-input-number>
        </el-form-item>

        <el-form-item prop="chairman" label="董事长">
          <el-select v-model="form.chairman" placeholder="请选择董事长" clearable filterable :style="{ width: '100%' }">
            <el-option v-for="item in chairmanOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="manager" label="总经理">
          <el-select v-model="form.manager" placeholder="请选择总经理" clearable filterable :style="{ width: '100%' }">
            <el-option v-for="item in managerOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="remarks" label="备注信息">
          <el-input v-model="form.remarks" type="textarea" :rows="3" :maxLength="255" placeholder="请输入备注信息" clearable></el-input>
        </el-form-item>
      </el-form>
      <!-- ❌ 不要自定义footer -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onSubmit" type="primary" v-show="mode != 'view'">保存</el-button>
          <el-button @click="onDialogClose" v-if="mode != 'view'">取消</el-button>
          <el-button @click="onDialogClose" v-if="mode == 'view'">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
/** 根据用户界面配置import组件 结束 */
import { getCompanyById, saveCompany, treeCompany } from '@/api/org/company'
import { listUserAll } from '@/api/sys/user'
import BaseUI from '@/views/components/baseUI'
import OperationIcon from '@/components/OperationIcon'
export default {
  extends: BaseUI,
  name: 'company-form',
  components: {
    OperationIcon
  },
  data() {
    return {
      // 操作模式 view/edit/add
      mode: 'add',

      form: this.initForm(),
      // 对话框属性变量
      visible: false,
      title: '公司',

      // 表单验证规则，根据数据库字段生成
      rules: {
        'code': [{ required: true, message: '编号不能为空', trigger: 'blur' }],
        'name': [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        'fullName': [{ required: true, message: '全称不能为空', trigger: 'blur' }]
      },

      // 选项变量，包含父级选项
      parentOptions: [],
      chairmanOptions: [],
      managerOptions: []
    }
  },
  props: {
    // 权限
    permission: {
      type: Object
    }
  },
  methods: {
    // 必须实现的方法
    onSubmit() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.doSave()
        } else {
          return false
        }
      })
    },
    // 必须实现的方法
    doSave() {
      this.setLoad()

      saveCompany(this.form)
        .then((responseData) => {
          if (responseData.code == 100) {
            this.visible = false
            this.showMessage({
              type: 'success',
              msg: '保存成功'
            })
            this.$emit('save-finished')
          } else {
            this.showMessage(responseData)
          }
          this.resetLoad()
        })
        .catch((error) => {
          this.outputError(error)
        })
    },
    // 必须实现的方法
    getFormById(id) {
      this.setLoad()
      return new Promise((resolve) => {
        getCompanyById(id)
          .then((responseData) => {
            let form = {}
            if (responseData.code == 100) {
              form = responseData.data
            } else {
              this.showMessage(responseData)
            }
            this.resetLoad()
            resolve(form)
          })
          .catch((error) => {
            this.outputError(error)
          })
      })
    },
    // 必须实现的方法
    onDialogClose() {
      this.visible = false
    },
    // 必须实现的方法
    onDialogOpen() {
      this.$nextTick(() => {
        this.$refs['editForm'].clearValidate()
      })
    },
    onParentChange() {
      let nodes = this.$refs['parentCascader'].getCheckedNodes()
      if (nodes.length > 0) {
        if (nodes[0] && nodes[0].data && nodes[0].data.children) {
          this.form.sort = (nodes[0].data.children.length + 1) * 10000
        } else if (nodes[0]) {
          this.form.sort = 10000
        } else {
          this.form.sort = (this.parentOptions.length + 1) * 10000
        }
      } else {
        this.form.sort = (this.parentOptions.length + 1) * 10000
      }
    },
    // 必须实现的方法 - 初始化表单数据
    initForm() {
      return {
        // 根据数据库字段生成
        id: null,
        code: '', // 编号
        name: '', // 名称
        fullName: '', // 全称
        parent: {
          id: null
        },
        ids: '',
        sort: 0, // 排序
        chairman: null, // 董事长
        manager: null, // 总经理
        remarks: '', // 备注信息
        createBy: '',
        createDate: '',
        updateBy: '',
        updateDate: '',
        delFlag: '0'
      }
    },
    // 必须实现的方法 - 打开查看模式
    async openView(id) {
      this.mode = 'view'
      this.title = `查看公司`
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      }
      this.initOptions(this.form)
      this.visible = true
    },
    // 必须实现的方法 - 打开编辑模式
    async openEdit(id) {
      this.mode = 'edit'
      this.title = `修改公司`
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      }
      this.initOptions(this.form)
      this.visible = true
    },
    // 必须实现的方法 - 打开新增模式
    openAdd(parent) {
      this.mode = 'add'
      this.title = `添加公司`
      this.form = this.initForm()

      // 有parent_id字段
      if(parent) {
        this.form.parent.id = parent.id
      }

      this.initOptions(this.form)
      this.visible = true
    },
    // 必须实现的方法 - 打开复制模式
    async openCopy(id) {
      this.mode = 'add'
      this.title = `添加公司`
      this.form = {
        ...this.initForm(),
        ...(await this.getFormById(id))
      }
      this.initOptions(this.form)
      this.form.id = null //把id设置为空，添加一个新的

      this.visible = true
    },
    
    // 有parent_id字段,必须实现的方法 - 初始化父级选项
    initParentOptions() {
      let search_List = {
        params: []
      }
      // filter条件
      search_List.params.push.apply(search_List.params, [
        {
          columnName: 'company.ids',
          queryType: 'not like',
          value: this.form.id ? this.form.id : null
        }
      ])

      treeCompany(search_List).then((responseData) => {
        if (responseData.code == 100) {
          this.parentOptions = responseData.data
        } else {
          this.showMessage(responseData)
        }
      })
    },

    // 初始化董事长和总经理选项
    initUserOptions() {
      let search_List = {
        params: []
      }

      listUserAll(search_List).then((responseData) => {
        if (responseData.code == 100) {
          this.chairmanOptions = responseData.data
          this.managerOptions = responseData.data
        } else {
          this.showMessage(responseData)
        }
      })
    },

    // 初始化自定义类型选择框选项变量
    initOptions(form) {
      this.initParentOptions()
      this.initUserOptions()
    }
  },
  watch: {
    parentOptions(newVal, oldVal) {
      if (newVal != oldVal && this.mode == 'add') {
        this.$nextTick(() => {
          this.onParentChange()
        })
      }
    }
  }
}
</script> 